package com.dragon.pear.config;

import com.dragon.common.spring.SingerAssist;
import com.dragon.common.spring.enhancers.advices.HttpRequestCommonExtractAdvice;
import lombok.NonNull;
import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.CommandLineRunner;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationListener;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.event.ContextRefreshedEvent;

import java.util.Arrays;

/**
 * 应用启动监听类
 * 项目启动后执行
 * 临时
 * 1. 打印所有Bean
 * 2. 测试公司级框架自动控制模块
 */
@Slf4j
@Configuration
public class AppStartedListener implements ApplicationListener<ContextRefreshedEvent>, CommandLineRunner {
    private final ApplicationContext context;
    private final SingerAssist singerAssist;


    public AppStartedListener(ApplicationContext context, SingerAssist singerAssist) {
        this.context = context;
        this.singerAssist = singerAssist;
    }

    @Override
    public void onApplicationEvent(@NonNull ContextRefreshedEvent event) {
        log.info("Application started.");
    }


    @Override
    public void run(String... args) throws Exception {
        //printAllBeans();
        // 测试公司级框架自动控制模块
        log.info(singerAssist.song());
    }

    private void printAllBeans() {
        log.info("🚀 Spring Container中的所有Bean:");
        log.info("=".repeat(80));

        String[] beanNames = context.getBeanDefinitionNames();
        Arrays.sort(beanNames);

        // 按类型分组统计
        for (String beanName : beanNames) {
            Object bean = context.getBean(beanName);
            String beanClassName = bean.getClass().getName();
            if (bean.getClass().equals(HttpRequestCommonExtractAdvice.class)) {
                log.info("📍 found beanName: {} → {}", beanName, beanClassName);
            }
        }

        log.info("=".repeat(80));
        log.info("📊 总计: {} 个Bean", beanNames.length);
    }

}